package bigk.pluzzdl.activity;

import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

import bigk.pluzzdl.ErrorListener;
import bigk.pluzzdl.ThreadCompleteListener;

public abstract class JPluzzDLThread implements Runnable{
	private final Set<ThreadCompleteListener> m_threadCompleteListeners =
			new CopyOnWriteArraySet<ThreadCompleteListener>();
	private final Set<ErrorListener> m_errorListeners=
			new CopyOnWriteArraySet<ErrorListener>();

	public final void addThreadCompleteListener(final ThreadCompleteListener listener) {
		m_threadCompleteListeners.add(listener);
	}
	
	public final void removeThreadCompleteListener(final ThreadCompleteListener listener) {
		m_threadCompleteListeners.remove(listener);
	}
	
	protected final void notifyThreadCompleteListeners() {
		for (ThreadCompleteListener listener : m_threadCompleteListeners) {
			listener.onThreadComplete(this);
		}
	}
	
	public final void addErrorListener(final ErrorListener listener) {
		m_errorListeners.add(listener);
	}
	
	public final void removeErrorListener(final ErrorListener listener)  {
		m_errorListeners.remove(listener);
	}
	
	protected final void notifyErrorListeners(Exception e) {
		for (ErrorListener listener: m_errorListeners) {
			listener.onError(e);
		}
	}

public void error(Exception e, String msg) {
		
		String _fullMsg="";
		if (msg!=null) {
			_fullMsg = msg + " : ";
		}
		_fullMsg += e.getMessage();
//		m_logger.log(Level.SEVERE,_fullMsg);	
		notifyErrorListeners(new RuntimeException(_fullMsg));
		notifyThreadCompleteListeners();
	}
}
